/*
 * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.trigram.uuid.bd;

import cn.trigram.asserts.AssertUtil;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * Allocate 64 bits for the UID(long)<br>
 * sign (fixed 1bit) -> deltaSecond -> workerId -> sequence(within the same second)
 * <br/>
 * 64位uid  不同位段分配器
 * @author yutianbao
 */
public class BitsAllocator {

  /**
   * 总共64位
   */
  public static final int TOTAL_BITS = 1 << 6;

  /**
   * 标记段位数 [sign-> second-> workId-> sequence]
   */
  private int signBits = 1;

  /**
   * 时间戳段位数
   */
  private final int timestampBits;

  /**
   * 机器段，位数
   */
  private final int workerIdBits;

  /**
   * 单位时间内序号段 位数
   */
  private final int sequenceBits;

  /**
   * 时间的最大增量值，因为时间并非从UTC 0 开始计算秒数。是从首次获取UID时开始的
   */
  private final long maxDeltaSeconds;

  /**
   * 最大的机器容量
   */
  private final long maxWorkerId;

  /**
   * 最大序号数
   */
  private final long maxSequence;

  /**
   * 时间戳偏移位置，从低位开始
   */
  private final int timestampShift;

  /**
   * 机器段偏移位置
   */
  private final int workerIdShift;

  /**
   * Constructor with timestampBits, workerIdBits, sequenceBits<br>
   * The highest bit used for sign, so <code>63</code> bits for timestampBits, workerIdBits,
   * sequenceBits。
   * <br/>
   * 注：timestampBits + workerIdBits + sequenceBits = 63
   */
  public BitsAllocator(int timestampBits, int workerIdBits, int sequenceBits) {
    // make sure allocated 64 bits
    int allocateTotalBits = signBits + timestampBits + workerIdBits + sequenceBits;
    AssertUtil.assertTrue(allocateTotalBits == TOTAL_BITS, "allocate not enough 64 bits");

    // initialize bits
    this.timestampBits = timestampBits;
    this.workerIdBits = workerIdBits;
    this.sequenceBits = sequenceBits;

    // 快速通过位运算计算出各个位段的最大值：等价于（-1 ^ (-1 << bits)）
    this.maxDeltaSeconds = ~(-1L << timestampBits);
    this.maxWorkerId = ~(-1L << workerIdBits);
    this.maxSequence = ~(-1L << sequenceBits);

    // 初始化各个位段的偏移量
    this.timestampShift = workerIdBits + sequenceBits;
    this.workerIdShift = sequenceBits;
  }

  /**
   * 根据  delta seconds & workerId & sequence 位数分配UID<br>
   * <b>Note that: </b>最高位sign 总是 0
   */
  public long allocate(long deltaSeconds, long workerId, long sequence) {

    return (deltaSeconds << timestampShift) | (workerId << workerIdShift) | sequence;
  }

  /**
   * Getters
   */
  public int getSignBits() {

    return signBits;
  }

  public int getTimestampBits() {

    return timestampBits;
  }

  public int getWorkerIdBits() {

    return workerIdBits;
  }

  public int getSequenceBits() {

    return sequenceBits;
  }

  public long getMaxDeltaSeconds() {

    return maxDeltaSeconds;
  }

  public long getMaxWorkerId() {

    return maxWorkerId;
  }

  public long getMaxSequence() {

    return maxSequence;
  }

  public int getTimestampShift() {

    return timestampShift;
  }

  public int getWorkerIdShift() {

    return workerIdShift;
  }

  @Override
  public String toString() {

    return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
  }

}